package com.game.doctor;

import java.io.File;
import java.io.IOException;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.game.globalconst.BIOrder;
import com.game.globalconst.OrderType;
import com.game.utils.FileUtils;
import com.ideaction.hotswap.HotSwapUtil;



/**
 * 不停机代码热更 jvm 探针技术
 * 只能修改现有的逻辑
 * 对方法中已有的field增加或者删除会失败
 * 新增方法也会失败
 * 
 * @author ZGame
 *
 */
public class JVMCodeHotFix implements OrderType {

	@Override
	public void action(BIOrder bIOrder) {
		String content = bIOrder.getContent();
		JSONObject jsonObj = JSON.parseObject(content);
		String javaFileName = jsonObj.getString("javaFileName");
		String javaContent = jsonObj.getString("javaContent");
		String javaFilePath = System.getProperty("user.dir") + File.separator + "lib" + File.separator
				+ javaFileName;
		try {
			FileUtils.writeFileText(javaFilePath, javaContent);
			JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
			compiler.run(null, null, null, javaFilePath);
		} catch (IOException e) {
			e.printStackTrace();
		}
		int index = javaFilePath.lastIndexOf(".");
		javaFilePath = javaFilePath.substring(0,index+1);
		HotSwapUtil.reloadClass(javaFilePath+"class");
	}
}
